<?php

namespace common\models;

use Yii;
use yii\db\ActiveRecord;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use Helper;

class MailTpl extends ActiveRecord
{
    const SCENARIO_ADD = 'add';
    const SCENARIO_EDIT = 'edit';

    const HTML_IS = 1;
    const HTML_NOT = 0;

    public static function tableName()
    {
        return '{{%mail_templates}}';
    }

    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['addtime']
                ]
            ],

        ];
    }

    public function rules()
    {
        return [
            ['appkey', 'checkAppkey', 'on' => [self::SCENARIO_ADD, self::SCENARIO_EDIT]],
            [['title'], 'required', 'on' => [self::SCENARIO_ADD, self::SCENARIO_EDIT], 'message' => Yii::t('code', '1063')],
            [['content'], 'required', 'on' => [self::SCENARIO_ADD, self::SCENARIO_EDIT], 'message' => Yii::t('code', '1064')],
            [['provider'], 'required', 'on' => [self::SCENARIO_ADD, self::SCENARIO_EDIT], 'message' => Yii::t('code', '1065')],
            [['provider'], 'checkProvider'],
            [['title'], 'string', 'max' => 100],
            [['content'], 'string'],
            [['content', 'title', 'provider'], 'filter', 'filter' => 'trim', 'skipOnArray' => true],
            ['is_html', 'in', 'range' => [self::HTML_IS, self::HTML_NOT], 'message' => Yii::t('code', '1067')],
            ['is_html', 'default', 'value' => self::HTML_IS],
        ];
    }

    public function checkAppkey($attribute, $params)
    {
        if ($this->appkey) {
            $row = Client::find()->where(['appkey' => $this->appkey])->one();
            if (!$row) {
                $this->addError($attribute, Yii::t('code', '1047'));
            }
        }
    }


    public function checkProvider($attribute, $param)
    {
        return true;
    }

    /**
     * 更新模版缓存
     */
    public static function updateTemplateCacheById()
    {
        $tplByIds = [];
        $smsTpls = self::find()->orderBy('id ASC')->all();
        if (!empty($smsTpls)) {
            foreach ($smsTpls as $k => $v) {
                $tplByIds[$v->id] = $v->attributes;
            }
            $cacheIdName = 'EmailTemplate';
            Yii::$app->redis->set($cacheIdName, json_encode($tplByIds));
        }
        return true;
    }

    /**
     * 更新邮件模块列表缓存
     * @param $appkey $appkey
     * @return bool 更新是否成功
     */
    public static function updateTemplateCacheGroupByAppkey($appkey)
    {
        $tplByTypes = [];
        $data = self::find()->where(['appkey' => $appkey])->all();
        if (!empty($data)) {
            foreach ($data as $k => $v) {
                $tplByTypes[$appkey][$v->id] = $v->attributes;
            }
        }
        if (!empty($tplByTypes)) {
            $cacheName = 'EmailTypesTemplate_' . $appkey;
            Yii::$app->redis->set($cacheName, json_encode($tplByTypes));
        }
        return true;
    }

    /**
     * 获取邮件模版缓存
     * @param array $serach 匹配信息
     * @return array $result 返回相符的结果
     */
    public static function getTemplateCache($serach = [], $setkey = false)
    {
        $result = [];
        $templates = Yii::$app->redis->get('EmailTemplate');
        if (empty($templates)) {
            $templates = self::find()->orderBy('id ASC')->asArray()->all();
        } else {
            $templates = json_decode($templates, true);
        }
        if (empty($templates)) {
            $result = [];
        } else if (!empty($serach)) {
            $serachKey = array_keys($serach);
            foreach ($templates as $k => $v) {
                $tflag = true;
                foreach ($serachKey as $ks) {
                    if ($v[$ks] != (string)$serach[$ks]) {
                        $tflag = false;
                        break;
                    }
                }
                if ($tflag) {
                    if ($setkey) {
                        $result[$v[$setkey]] = (array)$v;
                    } else {
                        $result[] = (array)$v;
                    }
                }
            }
        } else {
            foreach ($templates as $k => $v) {
                if ($setkey) {
                    $result[$v[$setkey]] = (array)$v;
                } else {
                    $result[] = (array)$v;
                }
            }

        }
        return $result;
    }
}


?>